<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2019/1/9
 * Time: 10:24
 */

namespace app\admin\service;


use app\admin\model\Admin;
use app\lib\exception\MysqlErrorException;
use Page\Page;
use think\Db;

class AdminService
{
    private $model;
    public function __construct()
    {
        $this->model = new Admin();
    }

    public function addAdmin($post_data)
    {
        if($post_data['id'] == ''){
            if($post_data['password_one'] !== $post_data['password_tow']){
                return [
                    'success' => false,
                    'msg' => '输入两次密码不一致!!!'
                ];
            }
            $name = $this->model
                ->where('username','=',$post_data['username'])
                ->find();
            if($name == true){
                return [
                  'success' => false,
                  'msg' => '用户名已存在!!!'
                ];
            }else{
                unset($post_data['id']);
                    $post_data['password'] = md5($post_data['password_tow']);
                    $post_data['add_time'] = now_time();
                Db::startTrans();
                try{
                    $this->model->create($post_data);
                    Db::commit();
                    return [
                        'success' => true,
                        'msg' => '添加成功!!!'
                    ];
                }catch (MysqlErrorException $exception){
                    Db::rollback();
                }
            }
        }else{
                array_key_exists('status',$post_data) ? $post_data['status'] = 1 : $post_data['status'] = 0;
                $md5_pwd = $this->model->find($post_data['id'])->value('password');
                if($md5_pwd !== md5($post_data['password_one'])){
                    return [
                        'success' => false,
                        'msg' => '原密码错误!!!'
                    ];
                }
                $post_data['password'] = md5($post_data['password_tow']);
                unset($post_data['password_one']);
                unset($post_data['password_tow']);
                $post_data['up_time'] = now_time();
            Db::startTrans();
            try{
                $this->model->where('id','=',$post_data['id'])
                    ->update($post_data);
                Db::commit();
                return [
                    'success' => true,
                    'msg' => '修改成功!!!'
                ];
            }catch (MysqlErrorException $exception){
                Db::rollback();
            }
        }
    }

    public function getAllAdminList($post_data)
    {
        $page = new Page($this->model,$post_data['page'],$post_data['limit']);
        $data = $page->layuiPage();
        return $data;
    }
}